(function ($) {
    //默认参数
    var defaluts = {
        searchName: '.ySearchSelect'
    };

    $.fn.extend({
        "ySearchSelect": function (options) {
            defaluts.searchName = options;
            var opts = $.extend({}, defaluts, options); //使用jQuery.extend 覆盖插件默认参数
            return this.each(function () {  //这里的this 就是 jQuery对象。这里return 为了支持链式调用
                init(opts);
            });

        }
    });
    let productInfo = [];
    //初始化插件
    function init(o){
        $(document).click(function(){
            var thin = this;
            $(".ySearchSelect table").hide();
            $(".ySearchSelect .input-text").hide();
            $(".ySearchSelect .layui-form.layui-border-box.layui-table-view").hide();
            $(".ySearchSelect i.layui-edge").removeClass("select");
        });

        $(o.searchName+" .layui-input").click(function(event){
            //阻止document点击事件
            event.stopPropagation();
            if($(this).siblings(".input-text").length <= 0){
                var str = '<div class="input-text">'+
                    '<input type="text" name="info" id="info" placeholder="输入关键字" class="layui-input">'+
                    '</div>';
                $(o.searchName).append(str);
            }
            if($(this).siblings("table").css("display") == "none"){
                var ids = $(o.searchName).attr("data-id");
                table.render({
                    elem: '#productcodeselect_'+ids,
                    id: 'productcodeselecttableid_'+ids,
                    url:'initStock/add/getProductInfo',
                    data: productInfo,
                    cols: [[
                        {field: 'productCode', width: 120, title: '产品编码'},
                        {field: 'specificationCode', width: 120, title: '规格编码'},
                        {field: 'productCname', width: 120, title: '中文名称'},
                        {field: 'productEname', width: 120, title: '英文名称'},
                        {field: 'directoryName', width: 120, title: '产品目录'}
                    ]],
                    height: 200
                });
                table.on('row(productcodeselecttable_'+ids+')', function(obj){
                    let data = obj.data;
                    let tableData = table.cache["storageproductstableid"];
                    $.each(tableData, function(index, value){
                        if(value.tempId == ids){
                            data.tempId = ids;
                            tableData[index] = data;
                        }
                    });
                    table.reload('storageproductstableid',{data:tableData});
                });
                $(this).siblings("i").addClass("select");
                $(this).siblings("table").show();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").show();
                $(this).siblings(".input-text").show();
            }else{
                $(this).siblings("i").removeClass("select");
                $(this).siblings("table").hide();
                $(this).siblings(".layui-form.layui-border-box.layui-table-view").hide();
                $(this).siblings(".input-text").hide();
            }
            $(o.searchName+" .input-text input").focus();
            $(o.searchName+" .input-text").width(605);

            //键盘监听事件
            $(o.searchName+" .input-text input").keyup(function(event){
                if(event.keyCode != 38 && event.keyCode != 40 && event.keyCode == 13){
                    ySearchSelectMate($(this).val(),o.searchName);
                }
            });
        });
    }

    //匹配搜索，不匹配则隐藏。
    function ySearchSelectMate(value, name){
        value = $.trim(value.toString()); // 去掉两头空格
        let ids = $(name).attr("data-id");
        //模糊查询表格并刷新
        table.reload('productcodeselecttableid_'+ids,{where: {
                info:value
        }});
    }
})(window.jQuery);

var form = layui.form, laydate = layui.laydate, annexList = [], upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id");
layui.use(['tableEdit'], function () {
    let tableEdit = layui.tableEdit;
    let layer = layui.layer;

    //仓库信息
    let warehouseList = [];
    let inStorePersonList = [];
    layer.ready(function () {
        $("#founder").val(user.name);
        //获取所有用户信息
        $.ajax({
            url:"otherOutStock/getAllUserInfo",
            success:function(data){
                if(data.status == 200){
                    inStorePersonList = data.data;
                    for(let i in data.data){
                        $('#inStoreCode').append(new Option(data.data[i].name, data.data[i].code));
                    }
                    $('#inStoreCode').val(user.code);
                    $('#inStorePerson').val(user.name);
                    form.render('select');
                }
            }
        });

        //获取仓库信息
        $.ajax({
            url:"transfer/getWarehouse",
            success:function(data){
                if(data.status == 200){
                    warehouseList = data.data;
                    for(let i in data.data){
                        $("#warehouseId").append("<option value=\"" + data.data[i].code + "\">" + data.data[i].name + "</option>");
                    }
                    form.render('select');
                }
            }
        });
    })

//表单初始值，修改时调用
    if (id != "") {
        form.val("editor-form", {
            "receiptno": "入库单号",
        })
    }

    //监听仓库下拉框
    form.on('select(warehouseId)', function (data) {
        if(data.value === ""){
            return;
        }
        $("#warehouseName").val(getWarehouseName(data.value));
    })
    //监听入库人下拉框
    form.on('select(inStoreCode)', function (data) {
        if(data.value === ""){
            return;
        }
        $("#inStorePerson").val(getInStorePerson(data.value));
    })

    function getInStorePerson(code){
        for(let i in inStorePersonList){
            if(inStorePersonList[i].code == code){
                return inStorePersonList[i].name;
            }
        }
        return "";
    }

    function getWarehouseName(code){
        for(let i in warehouseList){
            if(warehouseList[i].code == code){
                return warehouseList[i].name;
            }
        }
        return "";
    }

//监听提交
    form.on('submit(form-element)', function (data) {
        //向后台组装数据
        //获取头部表单数据
        let req = data.field;
        //获取附件数据
        let annexReqs = table.cache["attachmenttableid"];
        //获取库存表单信息数据
        let detail = table.cache["storageproductstableid"];
        if(detail.length > 0){
            for(let i in detail){
                let num = parseInt(i) + 1;
                //字段校验
                if(!checkData(detail[i], num)){
                    return false;
                }
            }
        }

        req["annexList"] = annexReqs;
        req["details"] = detail;
        let datas = JSON.stringify(req);
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:datas,
            url:"initStock/add",
            success:function(res){
                if(res.status == 200){
                    layer.msg("保存成功", {icon: 6});
                    setTimeout(function () {
                        //保存成功则刷新提交过来的界面 并关闭此页面
                        parent.detab("views/jsp/WarehouseManagement/initializethe.jsp");
                        parent.intab("views/jsp/WarehouseManagement/initializethe.jsp", "初始化")
                        parent.detab("views/jsp/WarehouseManagement/tpl/newupinitializethe.jsp" + (id == '' ? '' : '?id=' + id));
                    }, 1000)
                    return false;
                }else {
                    layer.msg(res.msg, {icon: 5});
                }
            }
        });
    });

    function checkData(data, i) {
        if(isEmpty(data.warehouseName)){
            layer.msg("第"+ i +"行：仓库名称不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.lotNo)){
            layer.msg("第"+ i +"行：批次号不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productCode)){
            layer.msg("第"+ i +"行：产品编码不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.specificationCode)){
            layer.msg("第"+ i +"行：规格编码不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.specificationExplanation)){
            layer.msg("第"+ i +"行：规格说明不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productNum)){
            layer.msg("第"+ i +"行：数量不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productUnit)){
            layer.msg("第"+ i +"行：单位不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.instoreUnitPrice)){
            layer.msg("第"+ i +"行：单价不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.productUnitPrice)){
            layer.msg("第"+ i +"行：成本单价不能为空", {icon: 5});
            return false;
        }
        if(isEmpty(data.supplierName)){
            layer.msg("第"+ i +"行：供应商名称不能为空", {icon: 5});
            return false;
        }
        return true;
    }
    //字段是否为空或者零
    function isEmpty(obj){
        if(typeof obj == "undefined" || obj == null || obj == "" || obj == 0){
            return true;
        }else{
            return false;
        }
    }

//--入库产品信息
    let initData = [];
    table.render({
        elem: '#storageproducts',
        id: 'storageproductstableid',
        data: initData,
        toolbar: '#storageproductstoolbar',
        cols: [[
            {field: 'img', title: '产品图片', width: 120, align: 'center', templet: '#imgTpl'},
            {field: 'warehouseName', width: 120, title: '仓库名称', templet: '#warehousenameselect'},
            {field: 'lotNo', width: 100, title: '批次号', edit: 'text'},
            {field: 'productCode', width: 120, title: '产品编码', templet: '#productcodeselect'},
            {field: 'specificationCode', width: 120, title: '规格编码', sort: true},
            {field: 'specificationExplanation', width: 120, title: '规格说明', edit: 'text'},
            {field: 'productNum', width: 80, title: '数量', edit: 'text'},
            {field: 'productUnit', width: 120, title: '单位', edit: 'text'},
            {field: 'instoreUnitPrice', width: 80, title: '单价', edit: 'text'},
            {field: 'moneySubtotal', width: 120, title: '金额小计', edit: 'text'},
            {field: 'productUnitPrice', width: 120, title: '成本单价', edit: 'text'},
            {field: 'shareCostPrice', width: 80, title: '分摊费用单价', edit: 'text'},
            {field: 'costAmount', width: 120, title: '成本小计', edit: 'text'},
            {field: 'trayNumber', width: 120, title: '托盘入数', edit: 'text'},
            {field: 'totalTray', width: 120, title: '总托盘', edit: 'text'},
            {field: 'supplierName', width: 120, title: '供应商名称', edit: 'text'},
            {field: 'color', width: 120, title: '颜色'},
            {field: 'productCname', width: 120, title: '中文名称'},
            {field: 'productEname', width: 120, title: '英文名称'},
            {field: 'productCdesc', width: 120, title: '中文描述'},
            {field: 'productEdesc', width: 120, title: '英文描述'},
            {field: 'memo', width: 210, title: '备注', edit: 'text'},
            {fixed: 'right', title: '操作', width: 120, align: 'center', toolbar: '#storageproductseditor'}]],
        page: true,
        height: 380
        , done: function (res, curr, count) {
            $(".layui-table select").parent(".layui-table-cell").css('overflow','visible')
            $(".layui-form-select").parents(".layui-table-cell").css('overflow','visible')
            hoverOpenImg();//显示大图
            for (var i = 0; i < res.data.length; i++) {
                var classs = ".y_" + res.data[i].tempId;
                $(classs).ySearchSelect(classs);
            }
            for(let i in warehouseList){
                $(".warehouse").append("<option value=\"" + warehouseList[i].code + "\">" + warehouseList[i].name + "</option>");
            }
            form.render('select');
        }
    })

    form.on("select(warehousenameselect_filter)", function (data) {
        let elem = data.othis.parents("tr");
        let dataIndex = elem.attr("data-index");
        let tableData = table.cache["storageproductstableid"];
        $.each(tableData, function (index, value) {
            if (value.LAY_TABLE_INDEX == dataIndex) {
                tableData[index]["warehouseId"] = data.value;
                tableData[index]["warehouseName"] = getWarehouseName(data.value);
            }
        });
    });


    table.on('edit(storageproductstable)', function (obj) {
        var old = $(this).prev().text();//旧值
        //判断数据类型
        if ((obj.field == "productNum" || obj.field == "instoreUnitPrice" || obj.field == "moneySubtotal" || obj.field == "productUnitPrice" || obj.field == "costAmount") && !isNumber(obj.value)) {
            layer.msg('请输入数字');
            $(this).val(old);
            return;
        }
    });

    function isNumber(val) {
        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    }

    table.on('tool(storageproductstable)', function (obj) {
        if (obj.event === 'del') {
            layer.confirm('确认删除?',confirmInfo(3,5), function (index) {
                let oldData =  table.cache["storageproductstableid"];
                for (var i = 0; i < oldData.length; i++) {
                    if (oldData[i].tempId == obj.data.tempId) {
                        oldData.splice(i, 1);
                        i--;
                        table.reload('storageproductstableid',{data : oldData});
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
            });

        }
    });

    function tobottomfn(id){
        let d=$("[lay-id='"+id+"'] .layui-table-main").get(0)
        let h=d.scrollHeight
        d.scrollTo(0,h)
    }

    table.on('toolbar(storageproductstable)', function (obj) {
        switch (obj.event) {
            case 'importproducts':
                layer.open({
                    type: 2,
                    area:["80%","95%"],
                    content: 'views/jsp/WarehouseManagement/tpl/importproducts.jsp'
                });
                break;
            case 'new':
                let oldData = table.cache["storageproductstableid"];
                let newData = {
                    "tempId": oldData.length + 1,
                    "img": "",
                    "warehouseName": "",
                    "lotNo": "",
                    "productCode": "",
                    "specificationCode": "",
                    "specificationExplanation": "",
                    "productNum": "",
                    "productUnit": "",
                    "instoreUnitPrice": "",
                    "moneySubtotal": "",
                    "productUnitPrice": "",
                    "shareCostPrice": "",
                    "costAmount": "",
                    "trayNumber": "",
                    "totalTray": "",
                    "supplierName": "",
                    "color": "",
                    "productCname": "",
                    "productEname": "",
                    "productCdesc": "",
                    "productEdesc": "",
                    "memo": ""
                };
                oldData.push(newData);
                table.reload('storageproductstableid', {data: oldData});
                tobottomfn("storageproductstableid");
                break;
        };
    });

    function hoverOpenImg() {
        var img_show = null; // tips提示
        $("body").delegate("td img", "mouseover", function () {
            var img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
            img_show = layer.tips(img, this, {
                tips: [2, 'rgba(41,41,41,.5)']
                , area: ['160px']
            });
        });
        $("body").delegate("td img", "mouseout", function () {
            layer.close(img_show);
        });
    }

//---附件
    table.render({
        elem: '#attachment'
        , data: annexList
        , toolbar: '#attachmenttoolbar'
        , cols: [[
            {field: 'fileName', title: '文件名', fixed: true}
            , {field: 'uploadTime', title: '上传日期', fixed: true}
            , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
        ]]
        , id: 'attachmenttableid'
        , height: 380
        , page: true
    });
    upload.render({
        elem: '#uploadfile'
        , url: 'transfer/uploadFile'
        , field: "uploadify"
        , accept: 'file'
        , multiple: true
        , auto: false
        , bindAction: '#testListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                $("#uploadlist").append(tr);
            });
        }
        , parseData: function(res){
            return {
                "code": res.status,
                "count": res.total,
                "data": res.data
            };
        }
        , done: function (res, index, upload) {
            var data = res.data;
            for(var i in data){
                if (data[i].status) { //上传成功
                    annexList.push(data[i]);
                    var tr = $("#uploadlist").find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    tds.eq(3).html(''); //清空操作
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
        }
        , error: function (index, upload) {
            var tr = $("#uploadlist").find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
        }
    });

    table.on('toolbar(attachmenttable)', function (obj) {
        switch (obj.event) {
            case 'uploadfile':
                $("#uploadlist").html(""); //清空上传列表数据
                layer.open({
                    type: 1,
                    title: "文件上传",
                    area: ['710px', '340px'],
                    content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                    , cancel: function (index, layero) {
                        table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                    }
                });
                break;
        };
    });
    table.on('tool(attachmenttable)', function (obj) {
        let data = obj.data;
        if (obj.event === 'download') { //下载
            let xmlHttpRequest = new XMLHttpRequest();
            let url = "wjinfo/downloadfile2?filename=" + data.filePath;
            xmlHttpRequest.open('GET', url, true);
            //设置请求头
            xmlHttpRequest.setRequestHeader("Content-type", "application/json")
            xmlHttpRequest.responseType = "blob";
            xmlHttpRequest.send(null);

            xmlHttpRequest.onload = function() {
                let content = xmlHttpRequest.response;
                // 组装a标签
                let elink = document.createElement("a");

                //设置文件下载路径
                elink.download = decodeURIComponent(data.fileName);
                elink.style.display = "none";
                let blob = new Blob([content], { type: 'application/force-download' });

                //解决下载不存在文件的问题，根据blob大小判断
                if(blob.size==0){
                    layer.msg('服务器没找到此文件，请联系管理员!');
                }else{
                    elink.href = window.URL.createObjectURL(blob);
                    document.body.appendChild(elink);
                    elink.click();
                    document.body.removeChild(elink);
                }

            }

        } else if (obj.event === 'del') {
            layer.confirm('确认删除?',
                confirmInfo(3,5), function (index) {
                    obj.del();
                    var id = data.id;
                    for (var i = 0; i < annexList.length; i++) {
                        if (annexList[i].id == id) {
                            annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                            i--; // 如果不减，将漏掉一个元素
                            break;
                        }
                    }
                    layer.msg("删除成功", {icon: 6});
                    layer.close(index);
                    table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
                });
        }
    });

//---操作日志
    let logData = [];
    table.render({
        elem: '#otherwarehouselog'
        , data: logData
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        , limit: 30//显示的数量
        , page: true
    });


//时间处理 初始赋值
    function getNowFormatDate() {
        let date = new Date();
        let separator = "-";
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        let currentDate = year + separator + month + separator + strDate;
        return currentDate;
    }

    let currentDate = getNowFormatDate();

    //创建时间
    laydate.render({
        elem: '#createDate',
        value: currentDate,
        min: currentDate,
        max: currentDate,
        btns: ['confirm']
    });

    //提示信息渲染
    function confirmInfo(icon, anim) {
        let data = {
            icon: icon,
            title: "提示",
            offset: "auto",
            skin: 'layui-layer-molv',
            anim: anim
        }
        return data;
    }
})